package com.freesky.web.manager.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.freesky.common.dao.entity.User;
import com.freesky.common.enums.ResponseEnum;
import com.freesky.common.exception.MyException;
import com.freesky.web.manager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;
/**
 *@author: 陈玉林
 *@date: 2019-01-10 17:07
 *@description:
 */
@Slf4j
@Component("authRealm")
public class MemberRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    @SuppressWarnings("unchecked")
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //获取用户名
        User user = (User) principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo auth=new SimpleAuthorizationInfo();
        //获得授权角色
        Set<String> roles = userService.getRoles(user.getUsername());
        auth.setRoles(roles);
        log.info("全部角色");
        for (String role:roles) {
            log.info(role);
        }
        //获得授权权限
        Set<String> permissions = userService.getPermissions(user.getUsername());
        auth.setStringPermissions(permissions);
        log.info("全部权限");
        for (String perm:permissions) {
            log.info(perm);
        }

        return auth;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        System.out.println("********** 1、用户登录认证：doGetAuthenticationInfo() **********");
        // 1、登录认证的方法需要先执行，需要用他来判断登录的用户信息是否合法
        String username = (String) token.getPrincipal();    // 取得用户名
        // 需要通过用户名取得用户的完整信息，利用业务层操作
        User user = new User().selectOne(new EntityWrapper().eq("state", 1).eq("username", username));
        if (user == null) {
            throw new MyException(ResponseEnum.SHIRO_UNKNOW_ACCOUNT,null,null);
        } else {    // 进行密码的验证处理
            String password = MyPasswordEncrypt.encryptPassword(new String((char[]) token.getCredentials()));
            // 将数据库中的密码与输入的密码进行比较，这样就可以确定当前用户是否可以正常登录
            if (user.getPassword().equals(password)) {
                AuthenticationInfo auth = new SimpleAuthenticationInfo(user, password, "memberRealm");
                return auth;
            } else {
                throw new MyException(ResponseEnum.SHIRO_ERROR_PASSWORD,null,null);
            }
        }
    }
}
